<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <span>试卷名称: {{ examName }}</span>
        </el-form>

        <!-- 新增|刷新 -->
        <div class="flex items-center justify-between mb-4">
            <div>
                <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
                <el-button type="primary" size="small" @click="handleBatchCreate">批量添加</el-button>
            </div>

            <el-tooltip effect="dark" content="刷新数据" placement="top">
                <el-button text @click="initTableData">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-tooltip>
        </div>

        <!-- 表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

            <!-- <el-table-column label="顺序" align="center">
                <template #default="{ row }">
                    {{ row.sort }}
                </template>
            </el-table-column> -->

            <!-- 1:单选题, 2:多选题, 3:简答题 -->
            <el-table-column label="问题类型" align="center">
                <template #default="{ row }">
                    {{ formatQuestionType(row.questionType) }}
                </template>
            </el-table-column>

            <el-table-column label="问题" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.question }}
                </template>
            </el-table-column>

            <el-table-column label="选项" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.questionOption }}
                </template>
            </el-table-column>

            <el-table-column label="答案" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.answer }}
                </template>
            </el-table-column>

            <el-table-column label="解析" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.questionExplain }}
                </template>
            </el-table-column>

            <!-- <el-table-column label="该题目在此考试中的分值" align="center">
                <template #default="{ row }">
                    {{ row.questionScore }}
                </template>
            </el-table-column> -->

            <el-table-column label="操作" width="320" align="center">
                <template #default="scope">
                    <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
                    <div v-else>
                        <el-button type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>
                        <el-popconfirm title="是否要删除该试题？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="handleDelete(scope.row.questionId)">
                            <template #reference>
                                <el-button text type="primary" size="small"
                                    :disabled="scope.row.state == '1'">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="initTableData" />
        </div>

        <!-- 新增|修改弹窗 -->
        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">

                <!-- <el-form-item label="试题排序" prop="sort">
                    <el-input-number v-model="form.sort" placeholder="试题排序" :min=1></el-input-number>
                </el-form-item> -->

                <el-form-item label="试题类型" prop="questionType">
                    <el-select v-model="form.questionType" placeholder="试题类型">
                        <el-option key="1" label="单选题" value="1"></el-option>
                        <el-option key="2" label="多选题" value="2"></el-option>
                        <el-option key="3" label="简答题" value="3"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="试题问题" prop="question">
                    <el-input v-model="form.question" placeholder="试题问题" type="textarea" :rows="3" maxlength="800"
                        show-word-limit></el-input>
                </el-form-item>

                <el-form-item label="试题选项" v-if="form.questionType != 3" prop="questionOption">
                    <el-input v-model="form.questionOption" placeholder="试题选项：中间通过英文分号分隔，表示不同选项！例如：语文;数学;英语;化学"
                        type="textarea" :rows="3" maxlength="800" show-word-limit></el-input>
                </el-form-item>

                <el-form-item label="试题答案" prop="answer">
                    <el-input v-model="form.answer" placeholder="试题答案：选项无需分隔！例如：A表示单选A；AB表示多选AB；当试题类型为简答题时，答案为字符串；" type="textarea"
                        :rows="3"></el-input>
                </el-form-item>

                <el-form-item label="试题解析" v-if="form.questionType != 3">
                    <el-input v-model="form.questionExplain" placeholder="试题解析" type="textarea" :rows="3"></el-input>
                </el-form-item>

                <!-- <el-form-item label="试题分值" prop="questionScore">
                    <el-input-number v-model="form.questionScore" placeholder="试题分值" :min=1></el-input-number>&nbsp;分
                </el-form-item> -->
            </el-form>
        </FormDrawer>

        <!-- 批量新增 -->
        <FormDrawer ref="batchFormDrawerRef" title="批量添加" @submit="handleBatchSubmit">
            <el-form :model="batchForm" ref="batchFormRef" :rules="batchFormRules" label-width="120px" :inline="false">
                <el-form-item label="试题类型" prop="questionType">
                    <el-select v-model="batchForm.questionType" placeholder="试题类型">
                        <el-option key="1" label="单选题" value="1"></el-option>
                        <el-option key="2" label="多选题" value="2"></el-option>
                        <el-option key="3" label="简答题" value="3"></el-option>
                    </el-select>
                </el-form-item>

                <!-- <el-form-item label="试题分值" prop="questionScore">
                    <el-input-number v-model="batchForm.questionScore" placeholder="试题分值" :min=1></el-input-number>&nbsp;分
                </el-form-item> -->

                <el-form-item label="试题内容" prop="text">
                    <el-input v-model="batchForm.text" placeholder="试题内容" type="textarea" :rows="20"></el-input>
                </el-form-item>
            </el-form>
        </FormDrawer>
    </el-card>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import FormDrawer from "~/components/FormDrawer.vue"
import { toast, toastWarn } from "~/composables/util"
import { useStore } from 'vuex'
import { api_examConfig_list, api_examQuestion_list, api_examPaper_by_id, api_examQuestion_add, api_examQuestion_update, api_examQuestion_delete,api_examQuestion_batchAdd } from "~/api/exam/examPaper"

//store存储
const store = useStore()

//试卷名称
const examName = ref(null)

// 表格分页数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)

// 查询条件
const searchForm = reactive({
    configId: null,
    page: currentPage.value,
    size: limit.value,
})

// 生命周期函数
onMounted(() => {
    if (null == store.state.configId) {
        toastWarn("试卷模版ID不能为空")
        return
    }
    //赋值
    searchForm.configId = store.state.configId

    //获取考试模版信息
    initExamPaperData(searchForm.configId)

    //初始化列表数据
    initTableData()
})

// 表单部分
// 是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
    sort: 1,
    configId: null,
    question: null,
    questionOption: null,
    answer: null,
    questionExplain: null,
    questionType: "1",
    // questionScore: 1,
})

//执行表单校验
const rules = {
    sort: [
        { required: true, message: '试题排序不能为空', trigger: 'change' }
    ],
    question: [
        { required: true, message: '试题问题不能为空', trigger: 'change' }
    ],
    answer: [
        { required: true, message: '试题答案不能为空', trigger: 'change' }
    ],
    questionExplain: [
        { required: true, message: '试题解析不能为空', trigger: 'change' }
    ],
    questionType: [
        { required: true, message: '试题类型不能为空', trigger: 'change' }
    ],
    // questionScore: [
    //     { required: true, message: '试题分值不能为空', trigger: 'change' }
    // ],
    questionOption: [
        { required: true, message: '试题选项不能为空', trigger: 'change' }
    ],
}

//提交表单
const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) return
        //loading
        formDrawerRef.value.showLoading()
        //configId
        form.configId = searchForm.configId
        const fun = editId.value == 0 ? api_examQuestion_add(searchForm.configId, form) : api_examQuestion_update(editId.value, form)
        fun.then(res => {
            toast(drawerTitle.value + "成功")
            //修改刷新当前页，新增刷新第一页
            initTableData(editId.value ? false : 1)
            formDrawerRef.value.close()
        })
            .finally(() => {
                //close loading
                formDrawerRef.value.hideLoading()
            })
    })
}

// 新增按钮点击事件
const handleCreate = () => {
    //修改标记置为0
    editId.value = 0
    resetForm({
        sort: 1,
        question: null,
        questionOption: null,
        answer: null,
        questionExplain: null,
        questionType: "1",
        // questionScore: 1,
    })
    //打开弹窗
    formDrawerRef.value.open()
}


// 批量表单部分
const batchFormDrawerRef = ref(null)
const batchFormRef = ref(null)
const batchForm = reactive({
    questionType: "1",
    // questionScore: 1,
    text: null
})

//执行表单校验
const batchFormRules = {
    questionType: [
        { required: true, message: '试题类型不能为空', trigger: 'change' }
    ],
    // questionScore: [
    //     { required: true, message: '试题分值不能为空', trigger: 'change' }
    // ],
    text: [
        { required: true, message: '试题内容不能为空', trigger: 'change' }
    ]
}

//提交表单
const handleBatchSubmit = () => {
    //表单校验
    batchFormRef.value.validate((valid) => {
        if (!valid) return
        //loading
        batchFormDrawerRef.value.showLoading()
        const fun = api_examQuestion_batchAdd(searchForm.configId, batchForm)
        fun.then(res => {
            toast("批量添加成功")
            initTableData(editId.value ? false : 1)
            batchFormDrawerRef.value.close()
        })
        .finally(() => {
            //close loading
            batchFormDrawerRef.value.hideLoading()
        })
    })
}

// 批量新增试题
const handleBatchCreate = () => {
    batchForm.questionType = "1"
    batchForm.text = null
    if (batchFormRef.value) {
        batchFormRef.value.resetFields()
    }
    //打开弹窗
    batchFormDrawerRef.value.open()
}

// 重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

//获取考试模版信息
function initExamPaperData(configId) {
    // api_examPaper_by_id(configId).then(res => {
    //     // console.log(res.records[0].examName)
    //     examName.value = res.paperName
    // })
    let paramIo = {}
    paramIo.configId = configId
    api_examConfig_list(paramIo)
    .then(res => {
        if (res) {
            // console.log(JSON.stringify(res))
            examName.value = res.records[0].examName
        }
    })
}

// 获取数据
function initTableData(p = null) {
    //指定页码是否为空
    if (typeof p == "number") {
        currentPage.value = p
    }

    loading.value = true
    searchForm.page = currentPage.value

    api_examQuestion_list(searchForm)
        .then(res => {
            if (res) {
                tableData.value = res.records
                total.value = Number(res.total)
            } else {
                tableData.value = []
                total.value = 0
            }
        })
        .finally(() => {
            loading.value = false
        })
}

// 编辑
const handleEdit = (row) => {
    editId.value = row.questionId
    resetForm(row)
    formDrawerRef.value.open()
}

// 删除
const handleDelete = (id) => {
    loading.value = true
    api_examQuestion_delete(id).then(res => {
        toast("删除成功")
        initTableData()
    })
        .finally(() => {
            loading.value = false
        })
}

const formatQuestionType = (type) => {
    if (type == 1) {
        return "单选题"
    } else if (type == 2) {
        return "多选题"
    } else if (type == 3) {
        return "简答题"
    }
    return "-"
}
</script>

<style scoped>
.hide ::v-deep .el-upload--picture-card {
    display: none;
}
</style>